package com.servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.beans.Person;
import com.bussiness.PersonBussinessProxy;
import com.constants.Constants;
import com.constants.UIMessages;
import com.constants.ServiceEndPoints;
import com.exceptions.InvalidUserNamePasswordException;
import com.exceptions.PasswordNotMatchingException;
import com.exceptions.ServiceUnavailableException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.validations.Validations;

/**
 * Servlet implementation class SignInServlet
 */
public class SignInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	PersonBussinessProxy personBI = new PersonBussinessProxy();
	       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignInServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{
			RequestDispatcher dispatcher;
			HttpSession session = request.getSession(true);
			session.setMaxInactiveInterval(Constants.sessionTimeOut);
			Person personData = new Person();
			boolean invalid = false;
			personData = getInputData(request);
			Person validatedDetails = null;
			if(validateForm(request,personData))
			{
				personBI.setEndpoint(ServiceEndPoints.PersonEndPoint);
				try
				{
					//Encrypt password before sending the data to network
					byte[] encryptedpassword = personBI.encryptPassword(personData.getPassword());
					personData.setPassword(Base64.encode(encryptedpassword));
					
					try
					{
						validatedDetails = new Person();
						validatedDetails = personBI.validateUser(personData);
					}
					catch(PasswordNotMatchingException ex)
					{
						invalid = true;
						request.setAttribute("emailException", UIMessages.INVALID_PASSWORD_MATCH);
					}
					catch(InvalidUserNamePasswordException ex)
					{
						invalid = true;
						request.setAttribute("emailException", UIMessages.INVALID_EMAILID_PASSWORD);
					}
					catch(ServiceUnavailableException ex)
					{
						invalid = true;
						request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
					}
					if(validatedDetails != null)
					{
						//Store User data to the session
						session.setAttribute("Name", validatedDetails.getFirstName() + "," + validatedDetails.getLastName());
						if(validatedDetails.getLastLoggedIn() != null)
							session.setAttribute("LastLoggedIn",validatedDetails.getLastLoggedIn());
						session.setAttribute("PersonData", validatedDetails);
						session.setAttribute("CustomerType", validatedDetails.getCustomerType());
						session.setAttribute("MembershipId", validatedDetails.getMemberShipNumber());
						session.removeAttribute("ServerException");
					}
					else
					{
						invalid = true;
						request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
					}
				}
				catch(Exception e)
				{
					invalid = true;
					request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
				}
				
				if(invalid)
				{
					dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
					dispatcher.forward(request, response);
				}
				else
				{
					dispatcher = getServletContext().getRequestDispatcher("/subPages.jsp");
					dispatcher.forward(request, response);
				}
				
			}
			else
			{
				dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
				dispatcher.forward(request, response);
				
			}
		}
		catch(Exception e)
		{
			request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
			dispatcher.forward(request, response);
		}
	}
	public Person getInputData(HttpServletRequest request)
	{
		
		Person userData = new Person();
		try
		{
			userData.setEmailId(request.getParameter("emailId").toString());
			userData.setPassword(request.getParameter("password1").toString());
			return userData;
		}
		catch(Exception e)
		{
			request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
			return null;
		}
		
	}
	
	public boolean validateForm(HttpServletRequest request,Person userData)
	{
		boolean bool=true;	
	
		try
		{
			if(!Validations.validateEmail(userData.getEmailId()))
			{
				request.setAttribute("emailException", UIMessages.INVALID_EMAILID_PASSWORD);
				request.setAttribute("emailId", userData.getEmailId());
				bool = false;
			}
			if(!Validations.validatePassword(userData.getPassword()))
			{
				request.setAttribute("emailException", UIMessages.INVALID_EMAILID_PASSWORD);
				bool = false;
			}
			return bool;
		}
		catch(Exception e)
		{
			request.setAttribute("emailException", UIMessages.SERVICE_UNAVAILABLE);
			return false;
		}
		
	}
	
	
}
